package com.phiture.erp.sale.web.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.phiture.erp.basic.api.pojo.resp.ErpCustomerResp;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.service.ErpCustomerApi;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleOrderPageReqDTO;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleOrderSaveReqDTO;
import com.phiture.erp.sale.core.pojo.vo.ErpSaleOrderRespVO;
import com.phiture.erp.sale.core.service.ErpSaleOrderService;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderDO;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderItemDO;
import com.phiture.erp.stock.api.service.ErpStockApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;

/**
 * @author YH
 * @date 2025/4/8
 */

@Tag(name = "管理后台 - ERP 销售订单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/sale-order")
public class ErpSaleOrderController {
    private final ErpSaleOrderService saleOrderService;
    private final AdminUserApi adminUserApi;
    private final ErpMaterialApi erpMaterialApi;
    private final ErpCustomerApi erpCustomerApi;
    private final ErpStockApi stockApi;

    @PostMapping("/create")
    @Operation(summary = "创建销售订单")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:create')")
    public CommonResult<Long> createSaleOrder(@Valid @RequestBody ErpSaleOrderSaveReqDTO createReqDTO) {
        return success(saleOrderService.createSaleOrder(createReqDTO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新销售订单")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:update')")
    public CommonResult<Boolean> updateSaleOrder(@Valid @RequestBody ErpSaleOrderSaveReqDTO updateReqDTO) {
        saleOrderService.updateSaleOrder(updateReqDTO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新销售订单的状态")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:update-status')")
    public CommonResult<Boolean> updateSaleOrderStatus(@RequestParam("id") Long id,
                                                       @RequestParam("status") Integer status) {
        saleOrderService.updateSaleOrderStatus(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除销售订单")
    @Parameter(name = "ids", description = "编号数组", required = true)
    @PreAuthorize("@ss.hasPermission('erp:sale-out:delete')")
    public CommonResult<Boolean> deleteSaleOrder(@RequestParam("ids") List<Long> ids) {
        saleOrderService.deleteSaleOrder(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得销售订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:query')")
    public CommonResult<ErpSaleOrderRespVO> getSaleOrder(@RequestParam("id") Long id) {
        ErpSaleOrderDO saleOrder = saleOrderService.getSaleOrder(id);
        if (saleOrder == null) {
            return success(null);
        }
        List<ErpSaleOrderItemDO> saleOrderItemList = saleOrderService.getSaleOrderItemListByOrderId(id);
        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(saleOrderItemList, ErpSaleOrderItemDO::getMaterialId));
        return success(BeanUtils.toBean(saleOrder, ErpSaleOrderRespVO.class, saleOrderVO ->
                saleOrderVO.setItems(BeanUtils.toBean(saleOrderItemList, ErpSaleOrderRespVO.Item.class, item -> {
                    BigDecimal stockCount = stockApi.getStockCount(item.getMaterialId());
                    item.setStockCount(stockCount != null ? stockCount : BigDecimal.ZERO);
                    MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()));
                }))));
    }

    @GetMapping("/page")
    @Operation(summary = "获得销售订单分页")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:query')")
    public CommonResult<PageResult<ErpSaleOrderRespVO>> getSaleOrderPage(@Valid ErpSaleOrderPageReqDTO pageReqDTO) {
        PageResult<ErpSaleOrderDO> pageResult = saleOrderService.getSaleOrderPage(pageReqDTO);
        return success(buildSaleOrderVOPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出销售订单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:sale-out:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSaleOrderExcel(@Valid ErpSaleOrderPageReqDTO pageReqDTO,
                                     HttpServletResponse response) throws IOException {
        pageReqDTO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpSaleOrderRespVO> list = buildSaleOrderVOPageResult(saleOrderService.getSaleOrderPage(pageReqDTO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "销售订单.xls", "数据", ErpSaleOrderRespVO.class, list);
    }

    private PageResult<ErpSaleOrderRespVO> buildSaleOrderVOPageResult(PageResult<ErpSaleOrderDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 订单项
        List<ErpSaleOrderItemDO> saleOrderItemList = saleOrderService.getSaleOrderItemListByOrderIds(
                convertSet(pageResult.getList(), ErpSaleOrderDO::getId));
        Map<Long, List<ErpSaleOrderItemDO>> saleOrderItemMap = convertMultiMap(saleOrderItemList, ErpSaleOrderItemDO::getOrderId);
        // 1.2 物料信息
        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(saleOrderItemList, ErpSaleOrderItemDO::getMaterialId));
        // 1.3 客户信息
        Map<Long, ErpCustomerResp> customerMap = erpCustomerApi.getCustomerMap(
                convertSet(pageResult.getList(), ErpSaleOrderDO::getCustomerId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), saleOrder -> Long.parseLong(saleOrder.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpSaleOrderRespVO.class, saleOrder -> {
            saleOrder.setItems(BeanUtils.toBean(saleOrderItemMap.get(saleOrder.getId()), ErpSaleOrderRespVO.Item.class,
                    item -> MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()))));
            saleOrder.setMaterialNames(CollUtil.join(saleOrder.getItems(), "，", ErpSaleOrderRespVO.Item::getMaterialName));
            MapUtils.findAndThen(customerMap, saleOrder.getCustomerId(), customer -> saleOrder.setCustomerName(customer.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(saleOrder.getCreator()), user -> saleOrder.setCreatorName(user.getNickname()));

            // 根据销售订单ID，查出销售订单项produceInQty之和
            List<ErpSaleOrderItemDO> OnesaleOrderItemList = saleOrderService.getSaleOrderItemListByOrderId(saleOrder.getId());
            // 求出saleOrderItemList的入库数量之和
            BigDecimal inCount = getSumValue(OnesaleOrderItemList, ErpSaleOrderItemDO::getProduceInQty, BigDecimal::add);
            saleOrder.setProduceInQty(inCount);
        });
    }
}
